﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AllDeal.DataAccess;

namespace AllDeals.CollectorEngine.HotDeal {
    public class HotDealEngine {
        public void Run() {
            HotDealAnalyzer analyzer = new HotDealAnalyzer();
            List<Product> hcmcProducts = analyzer.GetProducts(HotDealAnalyzer.HANOI_URL);
            List<Product> hnProducts = analyzer.GetProducts(HotDealAnalyzer.HCM_URL);
            hcmcProducts.AddRange(hnProducts);
            Save(hcmcProducts);
        }
        private void Save(List<Product> products) {
            using (var context = new AllDealsEntities()) {
                List<string> originUrls = products.Select(x => x.OriginalUrl).ToList();
                List<string> existedUrl = context.Products.Where(x => originUrls.Contains(x.OriginalUrl))
                                                 .Select(x => x.OriginalUrl).ToList();
                products.RemoveAll(x => existedUrl.Contains(x.OriginalUrl));
                foreach (Product product in products) {
                    context.Products.Add(product);
                }
                context.SaveChanges();
            }
        }
    }
}
